import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import '../models/user.dart';

class AuthService {
  // 动态确定API地址 - 支持Web和其他平台
  static String get baseUrl {
    // 在Web环境下，使用当前域名或localhost
    if (kIsWeb) {
      return 'http://localhost:5000/api';
    }
    return 'http://localhost:5000/api';
  }

  static const String tokenKey = 'auth_token';

  final Dio _dio = Dio();

  AuthService() {
    _dio.options.baseUrl = baseUrl;
    _dio.options.headers['Content-Type'] = 'application/json';
    _dio.options.connectTimeout = const Duration(seconds: 10);
    _dio.options.receiveTimeout = const Duration(seconds: 10);

    // Web环境特殊配置
    if (kIsWeb) {
      _dio.options.headers['Access-Control-Allow-Origin'] = '*';
      _dio.options.headers['Access-Control-Allow-Methods'] =
          'GET,PUT,POST,DELETE,OPTIONS';
      _dio.options.headers['Access-Control-Allow-Headers'] =
          'Content-Type,Authorization,X-Requested-With,Accept,Origin';
    }
  }

  Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(tokenKey);
  }

  Future<void> saveToken(String token) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(tokenKey, token);
  }

  Future<void> clearToken() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(tokenKey);
  }

  Future<User> login(String email, String password) async {
    try {
      print('尝试登录: $email'); // 调试信息

      final response = await _dio.post(
        '/auth/login',
        data: {'email': email, 'password': password},
      );

      print('登录响应: ${response.statusCode} - ${response.data}'); // 调试信息

      if (response.statusCode == 200 && response.data['success'] == true) {
        final token = response.data['token'];
        final userData = response.data['user'];
        final user = User.fromJson(userData);

        await saveToken(token);
        return user;
      } else {
        throw Exception(response.data['message'] ?? '登录失败');
      }
    } on DioException catch (e) {
      print('网络异常: ${e.type} - ${e.message}'); // 调试信息

      if (e.response?.statusCode == 401) {
        throw Exception('邮箱或密码错误');
      } else if (e.response?.statusCode == 404) {
        throw Exception('服务器地址不正确，请确保后端服务已启动');
      } else if (e.type == DioExceptionType.connectionTimeout) {
        throw Exception('连接超时，请检查网络连接');
      } else if (e.type == DioExceptionType.receiveTimeout) {
        throw Exception('请求超时，请重试');
      } else if (e.type == DioExceptionType.connectionError) {
        throw Exception('无法连接到服务器，请确保后端服务运行在 localhost:5000');
      } else {
        throw Exception('网络错误: ${e.message ?? '请检查网络连接'}');
      }
    } catch (e) {
      print('登录错误: $e'); // 调试信息
      throw Exception('登录失败: $e');
    }
  }

  Future<User> register(String name, String email, String password) async {
    try {
      print('尝试注册: $email'); // 调试信息

      final response = await _dio.post(
        '/auth/register',
        data: {'name': name, 'email': email, 'password': password},
      );

      print('注册响应: ${response.statusCode} - ${response.data}'); // 调试信息

      if (response.statusCode == 201 && response.data['success'] == true) {
        final token = response.data['token'];
        final userData = response.data['user'];
        final user = User.fromJson(userData);

        await saveToken(token);
        return user;
      } else {
        throw Exception(response.data['message'] ?? '注册失败');
      }
    } on DioException catch (e) {
      print('注册网络异常: ${e.type} - ${e.message}'); // 调试信息

      if (e.response?.statusCode == 409) {
        throw Exception('用户已存在');
      } else if (e.response?.statusCode == 404) {
        throw Exception('服务器地址不正确，请确保后端服务已启动');
      } else if (e.type == DioExceptionType.connectionTimeout) {
        throw Exception('连接超时，请检查网络连接');
      } else if (e.type == DioExceptionType.receiveTimeout) {
        throw Exception('请求超时，请重试');
      } else if (e.type == DioExceptionType.connectionError) {
        throw Exception('无法连接到服务器，请确保后端服务运行在 localhost:5000');
      } else {
        throw Exception('网络错误: ${e.message ?? '请检查网络连接'}');
      }
    } catch (e) {
      print('注册错误: $e'); // 调试信息
      throw Exception('注册失败: $e');
    }
  }

  Future<void> logout() async {
    await clearToken();
  }

  Future<bool> isLoggedIn() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }

  // 更新用户资料
  Future<User?> updateProfile({
    required String name,
    String? bio,
    String? phone,
    String? location,
  }) async {
    try {
      final token = await getToken();
      if (token == null) {
        throw Exception('未找到认证令牌');
      }

      print('更新用户资料: $name, $bio, $phone, $location');

      final response = await _dio.put(
        '/users/profile',
        data: {'name': name, 'bio': bio, 'phone': phone, 'location': location},
        options: Options(headers: {'Authorization': 'Bearer $token'}),
      );

      print('更新响应: ${response.statusCode} - ${response.data}');

      if (response.statusCode == 200) {
        final data = response.data;
        if (data['success'] == true && data['data'] != null) {
          return User.fromJson(data['data']['user']);
        }
      }

      throw Exception('更新失败');
    } on DioException catch (e) {
      print('更新用户资料网络异常: ${e.type} - ${e.message}');

      if (e.response?.statusCode == 401) {
        throw Exception('认证失败，请重新登录');
      } else if (e.response?.statusCode == 404) {
        throw Exception('用户不存在');
      } else if (e.type == DioExceptionType.connectionError) {
        throw Exception('无法连接到服务器');
      } else {
        throw Exception('网络错误: ${e.message ?? '请检查网络连接'}');
      }
    } catch (e) {
      print('更新用户资料失败: $e');
      rethrow;
    }
  }
}
